package com.wenc.psi.rvAdapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.wenc.psi.R;
import com.wenc.psi.pojo.Part;

import java.util.ArrayList;
import java.util.List;

public class PartAdapter extends RecyclerView.Adapter<PartAdapter.PartViewHolder> {
    List<Part> partList = new ArrayList<>();

    public void setPartList(List<Part> partList) {
        this.partList = partList;
    }

    @NonNull
    @Override
    public PartViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View itemView = layoutInflater.inflate(R.layout.cell_part, parent, false);
        return new PartViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull PartViewHolder holder, int position) {
        Part part = partList.get(position);
        holder.tvPartId.setText(String.valueOf(part.getId()));
        holder.tvPartName.setText(String.valueOf(part.getName()));
        holder.tvInventory.setText(String.valueOf(part.getInventory()));
        holder.tvModel.setText(String.valueOf(part.getModel()));
        holder.tvEngine.setText(String.valueOf(part.getEngine()));
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onItemClickListener != null) {
                    onItemClickListener.onItemChoiceClick(part);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        if (partList == null) return 0;
        return partList.size();
    }

    class PartViewHolder extends RecyclerView.ViewHolder{
        TextView tvPartId, tvPartName, tvInventory, tvModel, tvEngine;
        public PartViewHolder(@NonNull View itemView) {
            super(itemView);
            tvPartId = itemView.findViewById(R.id.tv_partId);
            tvPartName = itemView.findViewById(R.id.tv_partName);
            tvInventory = itemView.findViewById(R.id.tv_inventory);
            tvModel = itemView.findViewById(R.id.tv_model);
            tvEngine = itemView.findViewById(R.id.tv_engine);
        }
    }

    //创建接口
    private OnItemClickListener onItemClickListener;

    //定义接口
    public interface OnItemClickListener{
        //选择方法
        void onItemChoiceClick(Part part);
    }

    public void setOnItemClickListener(OnItemClickListener onItemClickListener){
        this.onItemClickListener = onItemClickListener;
    }
}
